import {Message} from 'element-ui'

const ResultType = {
  SUCCESS: 'SUCCESS',
  WARNING: 'WARNING',
  FAILURE: 'FAILURE',
  EXCEPTION: 'EXCEPTION'
}

export default function ({$axios, redirect}) {
  $axios.onRequest((config) => {
    config.headers.lang = window.localStorage.getItem('lang')
    console.log(config)
    return config
  })

  $axios.onResponse((response) => {
    const status = response.status
    // 状态码
    if (status === 200 || status === 304) {
      const respResult = response.data
      if (!respResult) {
        return
      }
      const resultMsg = respResult.message
      switch (respResult.result) {
        case ResultType.SUCCESS:
          if (resultMsg !== null) {
            Message.success(resultMsg)
          }
          if (respResult.data) {
            return respResult.data
          }
          return true
        case ResultType.WARNING:
          Message.warning(resultMsg)
          break
        case ResultType.FAILURE:
        case ResultType.EXCEPTION:
          Message.error(resultMsg)
          break
        default:
          Message.warning('未知请求结果！')
          break
      }
      return
    }
    if (status === 500) {
      Message.error('服务器出错，请联系管理员！')
    } else if (status === 504) {
      Message.error('连接超时，请重试！')
    } else if (status === 404) {
      Message.error('请求的链接不存在，请联系管理员！')
    } else {
      Message.error('发生未知错误！')
    }
    // redirect('/400')
  })

  $axios.onError((error) => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/400')
    }
  })
}